<script lang="ts" setup>
import { ListenerProp } from '@varlet/ui';
import { useToggle } from '@vueuse/shared';
import { useI18n } from 'vue-i18n';

// 定义 props
defineProps<{
    modelValue?: string;
    disabled?: boolean;
    readonly?: boolean;
    'onUpdate:modelValue'?: ListenerProp<(value: string) => void>;
}>();

// 定义事件
const emit = defineEmits(['update:modelValue']);

// 输入框的显示隐藏
const [inputVisible, onToggleVisible] = useToggle(false);

// v-model
const onClear = (value: string) => {
    emit('update:modelValue', value);
};
const onInput = (value: string, e: Event) => {
    emit('update:modelValue', value);
};

const { t } = useI18n();

// 校验规则，返回true表示通过校验
const rules = [
    (v: string) => {
        // 填写邀请码时校验位数是否在8-20内
        if (!!v && v.length < 8) {
            return t('form_referral_rule');
        }
        return true;
    },
];
</script>
<template>
    <div class="hl-input-box">
        <!-- 通过 Varspace 控制间隔 -->
        <VarSpace class="label" @click="() => onToggleVisible()" size="2">
            <span>{{ $t('form_referral_label') }}</span>
            <VarIcon :name="inputVisible ? 'menu-up' : 'menu-down'" transition="100" />
        </VarSpace>
        <!-- 动画可优化 -->
        <Transition :duration="100">
            <VarInput v-if="inputVisible" class="input" type="text" clearable maxlength="20" :hint="false" :line="false"
                :model-value="modelValue" :disabled="disabled" :readonly="readonly" :rules="rules" @clear="onClear"
                @input="onInput">
            </VarInput>
        </Transition>
    </div>
</template>
<style lang="scss">
@import './input.scss';
</style>
